import re

import requests
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views.decorators.csrf import csrf_exempt

from zhuce.models import Zhuce

def login(user,password):
    """模拟登录OA并获取前一工作日打卡记录"""
    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36"}
    formdata = {
        "login_username": user,
        "login_password": password,
    }
    url = "http://192.168.3.198:8699/seeyon/main.do?method=login"
    # 模拟登录OA并保存cookie信息
    ssion = requests.Session()
    responseRes = ssion.post(
        url,
        headers = headers,
        data= formdata
    )
    print(responseRes.text)
    msg = re.findall(r"无效的用户名或密码|该帐号仅剩下\d次登录尝试机会|账号被锁定，请稍后重试或联系管理员",responseRes.text)
    """oa退出登录url:http://192.168.3.198:8699/seeyon/main.do?method=logout"""
    # 退出本次登录
    ssion.get("http://192.168.3.198:8699/seeyon/main.do?method=logout", headers=headers)
    return msg


@csrf_exempt
def zhuce_user(request):
    method = request.method
    if method == 'GET':
        return render(request, 'zhuce.html')
    elif method == 'POST':
        user = request.POST.get('user')
        password = request.POST.get('password')
        # 验证oa的用户名或密码是否正确
        msg = login(user,password)
        # print(msg)
        if not msg :
            email = request.POST.get('email')
            try:
                zhuce_obj = Zhuce.objects.filter(name = user)
                if  not zhuce_obj:
                    with transaction.atomic():  # 开启事务，失败会自动回滚，并执行except中的代码
                        Zhuce.objects.create(
                            name=user,
                            password=password,
                            email=email
                        )
                        return JsonResponse({'code': 0, 'msg': 'Success'})
                else:
                    return JsonResponse({'code': 2, 'msg': '用户名已存在'})
            except Exception as e:
                return JsonResponse({'code': 1, 'msg': str(e)})
        else:
            if len(msg) == 2:
                msg = msg[0]+','+msg[1]
            else:
                msg = msg[0]
            # print(msg)
            return JsonResponse({'code': 3, 'msg': msg})